<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="选择门店" required>
              <a-cascader
                :options="departModel.departTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder=""
                :fieldNames="departModel.fieldNames"
                style="width: 190px"
                v-model="queryParam.selecteddeparts"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="商品编码" required>
              <a-input placeholder v-model="queryParam.itemCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="时间">
              <a-range-picker
                :ranges="{
                  昨日: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                  近7天: [moment().subtract(8, 'days'), moment().subtract(1, 'days')],
                  本月: [moment().startOf('month'), moment().subtract(1, 'days')],
                }"
                v-model="orderDateRange"
                @change="handleChange"
                :disabled-date="disabledDate"
              />
            </a-form-item>
          </a-col>
          
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search" style="margin-right:8px">查询</a-button>
              <!-- <a-tooltip title="请选择条件进行查询，最大支持60天跨度查询"><a-icon type="question-circle-o" style="font-size:16px"></a-icon></a-tooltip> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button type="primary" icon="download" @click="handleExportXls1('日营业数据')" v-if="(dataSource && dataSource.length != 0)">导出</a-button> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :footer="isQueryed ? renderTableFooter:null"
      >
        <span slot="inStockCnt" slot-scope="text, record">
          <a @click="handleInStockCntDetail(record)" v-if="text != 0 && record.orgName != '合计'">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="checkOutStockCnt" slot-scope="text, record">
          <a @click="handlecheckOutStockCntDetail(record)" v-if="text != 0 && record.orgName != '合计'">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="saleCnt" slot-scope="text, record">
          <a @click="handlecheckOrderCntDetail(record)" v-if="text != 0 && record.orgName != '合计'">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="refundCnt" slot-scope="text, record">
          <a @click="handlecheckRefundCntDetail(record)" v-if="text != 0 && record.orgName != '合计'">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="transInStockCnt" slot-scope="text, record">
          <a @click="handlecheckTransInCntDetail(record)" v-if="text != 0 && record.orgName != '合计'">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="transOutStockCnt" slot-scope="text, record">
          <a @click="handlecheckTransOutCntDetail(record)" v-if="text != 0 && record.orgName != '合计'">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="remainCnt" slot-scope="text, record">
          <a @click="handlecheckRemianDetail(record)" v-if="text != 0 && record.orgName != '合计'">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <ReportStockSumInStockCntDetail ref="modalFormInStockCnt"></ReportStockSumInStockCntDetail>
    <ReportStockSumReturnBillCntDetail ref="modalFormReturnBillCnt"></ReportStockSumReturnBillCntDetail>
    <ReportStockSumOrderCntDetail ref="modalFormSumOrderCnt"></ReportStockSumOrderCntDetail>
    <ReportStockSumRefundCntDetail ref="modalFormRefundCnt"></ReportStockSumRefundCntDetail>
    <ReportStockSumTransInCntDetail ref="modalFormTransInCnt"></ReportStockSumTransInCntDetail>
    <ReportStockSumTransOutCntDetail ref="modalFormTransOutCnt"></ReportStockSumTransOutCntDetail>
    <ReportStockSumRemainCntDetail ref="modalFormRemainCnt"></ReportStockSumRemainCntDetail>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import moment from 'moment'
import { getAction, downFile } from '@/api/manage'
import { queryDepartTreeList1 } from '@/api/api'
import ReportStockSumInStockCntDetail from './modules/ReportStockSumInStockCntDetail'
import ReportStockSumReturnBillCntDetail from './modules/ReportStockSumReturnBillCntDetail'
import ReportStockSumOrderCntDetail from './modules/ReportStockSumOrderCntDetail'
import ReportStockSumRefundCntDetail from './modules/ReportStockSumRefundCntDetail'
import ReportStockSumTransInCntDetail from './modules/ReportStockSumTransInCntDetail'
import ReportStockSumTransOutCntDetail from './modules/ReportStockSumTransOutCntDetail'
import ReportStockSumRemainCntDetail from './modules/ReportStockSumRemainCntDetail'
export default {
  name: 'ReportStockSumList',
  mixins: [JeecgListMixin],
  components: {
    ReportStockSumInStockCntDetail,
    ReportStockSumReturnBillCntDetail,
    ReportStockSumOrderCntDetail,
    ReportStockSumRefundCntDetail,
    ReportStockSumTransInCntDetail,
    ReportStockSumTransOutCntDetail,
    ReportStockSumRemainCntDetail,
  },
  data() {
    return {
      description: '库存统计报表',
      disableMixinCreated: true,
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      //这个汇总变量,元素改成下面方法定义的
      sumModel: {
        orgName: '-',
        shopName: '-',
        inStockCnt: 0,
        checkOutStockCnt: 0,
        realSaleCnt: 0,
        saleCnt: 0,
        refundCnt: 0,
        transInStockCnt: 0,
        transOutStockCnt: 0,
        remainCnt: 0,
      },
      footerDataSource: [],
      isQueryed: false,
      // 表头
      columns: [
        {
          title: '所属机构',
          align: 'center',
          dataIndex: 'orgName',
          width: 180,
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'shopName',
          width: 180,
        },
        {
          title: '发货数量',
          align: 'center',
          dataIndex: 'inStockCnt',
          scopedSlots: { customRender: 'inStockCnt' },
          width: 180,
        },
        {
          title: '返货数量',
          align: 'center',
          dataIndex: 'checkOutStockCnt',
          scopedSlots: { customRender: 'checkOutStockCnt' },
          width: 180,
        },
        {
          title: '销售数量',
          align: 'center',
          dataIndex: 'realSaleCnt',
          width: 180,
        },
        {
          title: '开单数量',
          align: 'center',
          dataIndex: 'saleCnt',
          scopedSlots: { customRender: 'saleCnt' },
        },
        {
          title: '退单数量',
          align: 'center',
          dataIndex: 'refundCnt',
          scopedSlots: { customRender: 'refundCnt' },
          width: 180,
        },
        {
          title: '调入数量',
          align: 'center',
          dataIndex: 'transInStockCnt',
          scopedSlots: { customRender: 'transInStockCnt' },
          width: 180,
        },
        {
          title: '调出数量',
          align: 'center',
          dataIndex: 'transOutStockCnt',
          scopedSlots: { customRender: 'transOutStockCnt' },
          width: 180,
        },
        {
          title: '当前店余数量',
          align: 'center',
          dataIndex: 'remainCnt',
          scopedSlots: { customRender: 'remainCnt' },
          width: 180,
        },
      ],
      orderDateRange: [],
      url: {
        list: '/report/sum/queryStockSum',
        sumUrl: '/report/sum/sumCollect',
        exportXlsUrl: '/report/daily/exportXls',
      },
    }
  },
  computed: {},
  created() {
    this.init()
  },
  methods: {
    moment,
    init() {
      this.queryParam = {}
      this.loadDepartTree()
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })

          // this.$set(this.queryParam,'selecteddeparts',[departList[0].id,'0'])
        }
      })
    },
    handleInStockCntDetail(record) {
      console.log('进入发货查询')
      this.assembleQueryParam()
      this.$nextTick(() => {
        this.$refs.modalFormInStockCnt.view(record, this.queryParam)
      })
      this.$refs.modalFormInStockCnt.title = '发货详情'
    },
    handlecheckOutStockCntDetail(record) {
      console.log('进入返货查询')
      this.assembleQueryParam()
      this.$nextTick(() => {
        this.$refs.modalFormReturnBillCnt.view(record, this.queryParam)
      })
      this.$refs.modalFormReturnBillCnt.title = '返货详情'
    },
    handlecheckOrderCntDetail(record) {
      console.log('进入开单数量查询')
      this.assembleQueryParam()
      this.$nextTick(() => {
        this.$refs.modalFormSumOrderCnt.view(record, this.queryParam)
      })
      this.$refs.modalFormSumOrderCnt.title = '开单详情'
    },
    handlecheckRefundCntDetail(record) {
      console.log('进入退货数量查询')
      this.assembleQueryParam()
      this.$nextTick(() => {
        this.$refs.modalFormRefundCnt.view(record, this.queryParam)
      })
      this.$refs.modalFormRefundCnt.title = '退货详情'
    },
    handlecheckTransInCntDetail(record) {
      console.log('进入调入数量查询')
      this.assembleQueryParam()
      this.$nextTick(() => {
        this.$refs.modalFormTransInCnt.view(record, this.queryParam)
      })
      this.$refs.modalFormTransInCnt.title = '调入详情'
    },
    handlecheckTransOutCntDetail(record) {
      console.log('进入调出数量查询')
      this.assembleQueryParam()
      this.$nextTick(() => {
        this.$refs.modalFormTransOutCnt.view(record, this.queryParam)
      })
      this.$refs.modalFormTransOutCnt.title = '调出详情'
    },
    handlecheckRemianDetail(record) {
      console.log('进入店余数量查询')
      this.assembleQueryParam()
      this.$nextTick(() => {
        this.$refs.modalFormRemainCnt.view(record, this.queryParam)
      })
      this.$refs.modalFormRemainCnt.title = '店余数量详情'
    },
    assembleQueryParam() {
      console.log(this.queryParam.selecteddeparts)
      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]
      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
      }

      if (!this.queryParam.orgIds) {
        this.$message.warning('门店必选')
        return false
      }

      if (!this.queryParam.itemCode) {
        this.$message.warning('商品编码必选')
        return false
      }

      // let beginTime = this.orderDateRange[0]
      // let endTime = this.orderDateRange[1]
      // let diffDays = endTime.diff(beginTime, 'day')
      // if (diffDays > 60) {
      //   this.$message.warning('最多支持60天跨度时间查询')
      //   return false
      // }

      return true
    },
    handleChange(date, dateString) {
      this.queryParam.beginDate = dateString[0]
      this.queryParam.endDate = dateString[1]
    },
    searchQuery1() {
      if (!this.assembleQueryParam()) {
        return
      }

      this.isQueryed = true
      this.loadData(1)
    },
    loadData(arg) {
      console.log('--ipagination--', this.ipagination)

      if (arg) {
        this.ipagination.current = 1
      }

      this.loading = true
      if (this.ipagination && this.ipagination.current > 1) {
        //分页查询不在多次查汇总
        this.loadList()
      } else {
        this.querySum().then((res) => {
          if (res.success) {
            this.sumModel = res.result
            this.sumModel.orgName = '合计'
            this.sumModel.shopName = '-'

            let newDataSource = []
            newDataSource.push(this.sumModel)

            this.footerDataSource = newDataSource
          } else {
            this.loading = false
          }
        })
        this.loadList()
      }

      console.log('sumModel', this.sumModel)
    },
    loadList(arg) {
      console.log('---loadData---')
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //获取查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    disabledDate(current) {
      console.log('current=', current)
      return current && current > moment().subtract(1, 'days')
    },
    searchReset1() {
      this.init()
    },
    async querySum() {
      console.log('---querySum---')
      let query = await getAction(this.url.sumUrl, this.queryParam)
      return query
    },
    // 渲染表格底部合计行
    renderTableFooter() {
      let h = this.$createElement
      return h('a-table', {
        ref: 'footerTable',
        props: {
          size: 'middle',
          rowKey: 'rowIndex',
          columns: this.columns,
          pagination: false,
          dataSource: this.footerDataSource,
          showHeader: false,
        },
      })
    },
    handleExportXls1(fileName) {
      if (!this.assembleQueryParam()) {
        return
      }

      this.handleExportXls(fileName)
    },
    handleExportDetailXls(fileName) {
      if (!this.checkExportParam()) {
        return
      }

      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length != 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportDetailXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
a {
  text-decoration: underline;
}
/deep/ .chart-data-list .ant-table-footer .ant-table-body {
  overflow: hidden !important;
}
/deep/ .ant-table-footer {
  padding: 0 !important;
  .ant-table-row {
    color: red;
  }
}
</style>